package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void save(@RequestBody UserFormDTO userFormDTO){
//        将dto拷贝到user
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("{id}")
    public void deleteById(@ApiParam("用户id") @PathVariable("id") Long id){
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("{id}")
    public UserVO getOneById(@ApiParam("用户id") @PathVariable("id") Long id){
//        User user = userService.getById(id);
//        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
//        return userVO;
        return userService.queryUserAndAddressById(id);
    }

    @ApiOperation("根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> getListByIds(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids){
        List<User> userList = userService.listByIds(ids);
        List<UserVO> userVOList = BeanUtil.copyToList(userList, UserVO.class);
        return userVOList;
    }

    @ApiOperation("根据id扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void updateMoneyByIds(
            @ApiParam("用户id") @PathVariable Long id,
            @ApiParam("扣减金额") @PathVariable Integer money
            ){
        userService.DeductBalance(id,money);
    }

    @ApiOperation("复杂条件查询用户接口")
    @GetMapping("/list")
    public List<UserVO> queryListByIds(
            UserQuery userQuery
            ){
        List<User> userList = userService.queryUsers(userQuery);
        List<UserVO> userVOList = BeanUtil.copyToList(userList, UserVO.class);
        return userVOList;
    }
}
